package dyyx;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {
	
	@GetMapping("/")
	public String hello() {
		return "hello springboot api,"+new Date();
	}

	@RequestMapping("/api")
	public Map api(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();
				
		Map resultMap = new LinkedHashMap();
		resultMap.put("method", request.getMethod());
		if(params!=null && !params.isEmpty()) {
			resultMap.putAll(params);
		}
		resultMap.put("now", LocalDateTime.now().toString());
		
		Map<String,String> headMap = getHeadMap(request);
		if(headMap!=null && !headMap.isEmpty()) {
			resultMap.putAll(headMap);
		}
		
		return resultMap;
	}
	
	@RequestMapping("/api2")
	public Map api2(HttpServletRequest request) {
		
		Enumeration<String>  names = request.getParameterNames();
		Map resultMap = new LinkedHashMap();
		resultMap.put("method", request.getMethod());

		if(names!=null) {
			
			while(names.hasMoreElements()) {
				String name = names.nextElement();
				String value = request.getParameter(name);
				if(value==null) {
					continue;
				}
				resultMap.put(name, value);
			}
		}
		
		resultMap.put("now", LocalDateTime.now().toString());
		
		Map<String,String> headMap = getHeadMap(request);
		if(headMap!=null && !headMap.isEmpty()) {
			resultMap.putAll(headMap);
		}
		
		return resultMap;
	}
		
	// @PostMapping("/api3")
	@RequestMapping("/api3")
	public Map api3(@RequestBody Map params,HttpServletRequest request) {
		Map resultMap = new LinkedHashMap();
		resultMap.put("method", request.getMethod());

		if(params!=null && !params.isEmpty()) {
			resultMap.putAll(params);
		}
		resultMap.put("now", LocalDateTime.now().toString());
		
		Map<String,String> headMap = getHeadMap(request);
		if(headMap!=null && !headMap.isEmpty()) {
			resultMap.putAll(headMap);
		}
		
		return resultMap;
	}
	
	private static Map<String,String> getHeadMap(HttpServletRequest request){
		Map<String,String> headMap = new LinkedHashMap<>();
		Enumeration<String>  names = request.getHeaderNames();		
        if(names!=null) {			
			while(names.hasMoreElements()) {
				String name = names.nextElement();
				String value = request.getHeader(name);
				if(value==null) {
					continue;
				}
				headMap.put(name, value);
			}
		}
		return headMap;
	}
}